//
//  ViewController.swift
//  Order
//
//  Created by Lazyloading on 2020/7/1.
//  Copyright © 2020 lazyloading. All rights reserved.
//

import UIKit
import SnapKit
import PKHUD
import QMUIKit
import LEEAlert
import DZNEmptyDataSet
import MJRefresh

class HomeController: UIViewController ,UITableViewDelegate,UITableViewDataSource,QMUINavigationControllerDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate{
    
    let kHomeCellID = "kHomeCellID";
    var rightButton : UIButton?
    var dataArray = [OrderListModel]();
    
    lazy var tableView : UITableView = {
        let table = UITableView.init(frame: self.view.bounds);
        
        table.backgroundColor = .white;
        table.delegate = self;
        table.dataSource = self;
        table.register(UITableViewCell.self, forCellReuseIdentifier: kLeftMenuCellID);
        table.registerNib("OrderRobCell", kHomeCellID);
        table.showsVerticalScrollIndicator = false;
        table.separatorStyle = .none;
        table.estimatedRowHeight = 0;
        table.estimatedSectionFooterHeight = 0;
        table.estimatedSectionHeaderHeight = 0;
        table.emptyDataSetSource = self;
        table.emptyDataSetDelegate = self;
        
        weak var weakSelf = self;
        table.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {
            weakSelf?.listDataRequest();
        });
        if #available(iOS 11.0, *) {
            table.contentInsetAdjustmentBehavior = .never
        } else {
            // Fallback on earlier versions
            self.automaticallyAdjustsScrollViewInsets = false;
        };
        return table;
    }();
    
    lazy var headView: HomeHeadView = {
        let head = Bundle.main.loadNibNamed("HomeHeadView", owner: nil, options: nil)?.first as! HomeHeadView;
        head.bounds.size.height = ISIPHONEX() ? 170 : 150;
        
        weak var weakSelf = self;
        head.orderSwitchBlock = { button in
            button.isSelected = !button.isSelected;
            
            if button.isSelected == true{
                
                weakSelf?.getUserinfo(completion: { (balance) in
                    if balance.int() > 0{
                        weakSelf?.rightButton?.setTitle("在线", for: .normal);
                        weakSelf?.listDataRequest();
                    }else{
                        button.isSelected = false;
                        let alert = UIAlertController.init(title: "温馨提示", message: "您的余额不足无法接单", preferredStyle: UIAlertController.Style.alert);
                        alert.addAction(UIAlertAction.init(title: "不充值", style: .destructive, handler: nil));
                        alert.addAction(UIAlertAction.init(title: "去充值", style: .default, handler: { (alert) in
                            let vc = RechargeController();
                            weakSelf!.navigationController?.pushViewController(vc, animated: true);
                        }))
                        weakSelf!.present(alert, animated: true, completion: nil);
                    }
                })
 
            }else{
                weakSelf?.rightButton?.setTitle("离线", for: .normal);
                weakSelf?.dataArray.removeAll();
                weakSelf?.tableView.reloadData();
            }
        }
        return head;
    }()
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.loadDefaultSetting();
        self.initSubViews();
        self.noticeRequest();
//        self.headView.orderBtnAction(self.headView.orderBtn);
//        self.listDataRequest();
    }
    
    // MARK: 👉🏻 🐷Life cycle🐷
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated);
        self.menuContainerViewController.sideMenuPanMode = .defaults;
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated);
        if self.headView.orderBtn.isSelected == true {
            self.listDataRequest();
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated);
        self.menuContainerViewController.sideMenuPanMode = .none
    }
    
    // MARK: 👉🏻 🐷System Delegate🐷
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count;
     }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 50;
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell =  tableView.dequeueReusableCell(withIdentifier: kHomeCellID) as! OrderRobCell;
        let model = self.dataArray[indexPath.row];
        cell.typeLabel.text = model.typeDesc();
        cell.moneyLabel.text = model.orderPrice;
        weak var weakSelf = self;
        cell.orderActionBlock = { button in
            weakSelf!.getUserinfo(completion: { balance in
                if  balance.double() >= (model.orderPrice?.double())!{
                    weakSelf?.reciveOrderRequest(model: model);
                }else{
                    HUD.flash(.label("余额不足，请充值"), delay: 1);
                }
            });
        }
        
        return cell;
    }
    // MARK: 👉🏻 🐷Custom Delegate🐷
    func navigationBarBackgroundImage() -> UIImage? {
        return UIImage.qmui_image(with: ZMColor.Orange.orange1);
    }
    
    func navigationBarShadowImage() -> UIImage? {
        return UIImage.qmui_image(with: .clear);
    }
    
    func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
        let param = [
            NSAttributedString.Key.font : UIFont.init(fontType: .regular, fontSize: 15),
            
        ]
        return NSAttributedString.init(string: "暂无订单",attributes: param);
    }
    
    func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
        return ZMImage("orderlist_empty");
    }
    
    func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool {
        return true;
    }
    // MARK: 👉🏻 🐷Event  Response🐷
    @objc func leftMenuAction(button : UIButton){

        
        self.menuContainerViewController.toggleLeftSideMenu {
            
        };
        
    }
    // MARK: 👉🏻 🐷Private Methods🐷
    
    //订单列表
    func  listDataRequest() {
        
        let param = ["orderStatus" : "0"];
        weak var weakSelf = self;
        MoyaRequest(.orderList(param), success: { (response :BaseResponse<[OrderListModel]>) in
            weakSelf?.tableView.mj_header?.endRefreshing();
            if response.respCode == 200{
                self.dataArray = response.data!;
                self.tableView.reloadData();
            }
            
        }) { (error) in
            weakSelf?.tableView.mj_header?.endRefreshing();
        }
    }

    ///接单
    func reciveOrderRequest(model : OrderListModel)  {
        weak var weakSelf = self;
        
        let alert = UIAlertController.init(title: "提示", message: "确定抢单吗？", preferredStyle: UIAlertController.Style.alert);
        alert.addAction(UIAlertAction.init(title: "取消", style: .destructive, handler: nil));
        alert.addAction(UIAlertAction.init(title: "确定", style: .default, handler: { (alert) in
            let vc = OrderDetailController();
            vc.orderId = model.orderId;
            weakSelf!.navigationController?.pushViewController(vc, animated: true);
        }))
        self.present(alert, animated: true, completion: nil);
    }
    
    //查看余额
    func getUserinfo(completion : @escaping(String) -> Void){
   
        MoyaRequest(.userInfo, success: { (response : BaseResponse<[String : Any]>) in
            if response.respCode == 200{
                let balance = "\(response.data!["balance"] ?? "")";
                completion(balance);
            }else{
                completion("");
            }
        }) { (error) in
            completion("");
        }
    }
    
    //公告请求
    func noticeRequest()  {
        weak var weakSelf = self;
        MoyaRequest(.notice, success: { (response : BaseResponse<NoticeModel>) in
            if response.respCode == 200{
                if response.data?.status?.int() == 1 {
                    weakSelf!.noticeAlert(model: response.data);
                }
            }
        }) { (error) in
            
        }
    }
    
    //公告弹窗
    func noticeAlert(model : NoticeModel?)  {
        let alertW = KWIDTH - 60;
        let alertH = KHEIGHT - (ISIPHONEX() ? 300  : 220);
        let notice = NoticeView.init(frame: CGRect.init(x: 0, y: 0, width: alertW, height: alertH));
        
        notice.titleLabel.text = model?.title;
        notice.contentLabel.text = model?.content;
        
        let alert = LEEAlert.alert()
        _ = alert.config.leeCustomView(notice)
            .leeHeaderInsets(UIEdgeInsets.init(top: 0, left: 0, bottom: 0, right: 0))
            .leeMaxWidth(alertW)
            .leeMaxHeight(alertH)
            .leeShow();
        
        notice.dismissBlock = { button in
            LEEAlert.close(completionBlock: nil);
        };
        
    }
    // MARK: 👉🏻 🐷Lazy loading🐷
    // MARK: 👉🏻 🐷Init SubViews🐷
    
    func loadDefaultSetting()  {
        self.view.backgroundColor = .white;
        self.navigationItem.title = "抢单";
        self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor : UIColor.white];
    }
    
    func initSubViews()  {

        let left = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 30, height: 30));
        left.contentMode = .scaleAspectFit;
        left.imageView?.contentMode =  .scaleAspectFit;
        left.addTarget(self, action: #selector(leftMenuAction(button:)), for: .touchUpInside);
        left.setImage(ZMImage("touxiang"), for: .normal);
        let item = UIBarButtonItem.init(customView: left);
        self.navigationItem.leftBarButtonItem = item;
        
        let right = UIButton.init(frame: CGRect.init(x: 0, y: 0, width: 30, height: 30));
        right.setTitle("离线", for: .normal)
        right.setTitleColor(.white, for: .normal);
        right.titleLabel?.font = UIFont.init(fontType: .regular, fontSize: 16);
        self.rightButton = right;
        let rightItem = UIBarButtonItem.init(customView: right);
        self.navigationItem.rightBarButtonItem = rightItem;
        
        self.view.addSubview(self.tableView);
        self.tableView.tableHeaderView = self.headView;
        self.layout();
        
    }
    
    func layout()  {

        //列表
        self.tableView.snp.makeConstraints { (make) in
            make.top.bottom.equalToSuperview();
            make.leading.equalToSuperview().offset(10);
            make.trailing.equalToSuperview().offset(-10);
        };
    }

}

